package com.dk.service.Impl;

import com.dk.mapper.TabRouteMapper;
import com.dk.pojo.TabRoute;
import com.dk.service.FavoriteRankService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.DefaultTypedTuple;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class FavoriteRankServiceImpl implements FavoriteRankService {
    @Autowired
    TabRouteMapper tabRouteMapper;
    @Autowired
    RedisTemplate redisTemplate;
    @Override
    public List<TabRoute> getInfoRank(Integer pageNum, Integer pageSize) {
        String key = "RouteForSet:";
        List<TabRoute> list = null;
        Gson gson = new Gson();
        Integer EveryPageNum= (pageNum-1)*pageSize;
        ZSetOperations opsForZSet = redisTemplate.opsForZSet();
        //从redis中查询
        if(redisTemplate.hasKey(key)){
            //查询总条数
            Long size = opsForZSet.size(key);
            list = new ArrayList<>();
            //获取set集合
            if (pageNum==1){
                Set<String> setForRoute = opsForZSet.reverseRange(key, 0, (long) pageNum *pageSize);
                //循环遍历set 使用gson将字符串转为对象再放入到list集合中
                for (String tabRoute : setForRoute) {
                    list.add(gson.fromJson(tabRoute, TabRoute.class));
                }
            }else {
                Set<String> setForRoute = opsForZSet.reverseRange(key, EveryPageNum+1, (long) pageNum *pageSize);
                //循环遍历set 使用gson将字符串转为对象再放入到list集合中
                for (String tabRoute : setForRoute) {
                    list.add(gson.fromJson(tabRoute, TabRoute.class));
                }
            }

        }else {
            //第一次访问从数据库查所有数据并存入redis
            list = tabRouteMapper.getInfoRank();
            for (TabRoute route : list) {
                String s = gson.toJson(route);
                //循环遍历插入zSet集合
                opsForZSet.add(key,s,route.getCount());
            }

        }

        return list;

    }

    @Override
    public PageInfo<TabRoute> getInfo(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<TabRoute> routes = tabRouteMapper.getInfoRank();
        PageInfo<TabRoute> pageInfo = new PageInfo<TabRoute>(routes);
        return pageInfo;
    }
}
